// pages/user-course/user-course-detail/course-appoint/course-appoint.js
const app = getApp()
const constant = require("../../../../constant.js")
const storage = require("../../../../utils/storage.js")
import Dialog from '../../../../miniprogram_npm/vant-weapp/dialog/index';

const currentDate = Date.parse(new Date());

Page({
  data: {
    show: {
      top: false,
    },
    qiniu: constant.resource.qiniu,
    currentDate: currentDate,
    showShop: false,
    showCoach: true,

  },
  onClose() {
    this.setData({
      showShop: false
    });
  },
  toggle(type) {
    this.setData({
      [`show.${type}`]: !this.data.show[type]
    });
  },
  toggleCoach() {
    this.setData({
      showCoach: !this.data.showCoach
    });
  },

  // selectCity: function(e) {
  //   var that = this;
  //   let name = e.currentTarget.dataset.name
  //   var activeDistrictName = that.data.districts[name][0]
  //   that.setData({
  //     activeCityName: name,
  //     //activeDistrictName: that.data.site.district,
  //     sites: that.getCitySite(name)
  //   })
  // },
  selecteCoach: function (e) {

    var that = this;
    let name = e.currentTarget.dataset.id
    let real_name = e.currentTarget.dataset.user
    console.log(name)
    that.setData({
      coach_id: name,
      selectedCoach: real_name,
    })
    // 
    // that.data.coaches
    var arr = that.data.coaches
    var elementPos = arr.map(function (x) {
      return x.id;
    }).indexOf(name);
    var objectFound = arr[elementPos];
    console.log('elementPos')
    console.log(elementPos)

    arr.splice(elementPos, 1);
    arr.unshift(objectFound);
    that.setData({
      coaches: arr,
    })

    wx.request({
      url: constant.api(app.globalData.pord).url+ '/xh/api/principle/get_date/',
      method: 'POST',
      data: {
        coach_id: that.data.coach_id,
        date: that.data.chooseDay,
        union_id: that.data.unionid,
        scheduleId: that.data.scheduleId,
        siteId: that.data.siteId,
      },
      dataType: 'json',
      responseType: 'text',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        //  success
        that.setData({
          times: res.data,
        });
        console.log(res.data)
        if (that.data.showCoach)
          that.toggleCoach();
      },
      fail: function (res) {
        wx.showToast({
          title: '请求数据失败',
          icon: 'none',
          duration: 1000
        });
      }
    })
  },
  toggleTopPopup() {
    if (this.data.show.date) {
      this.toggleDatePopup();
    }

    this.setData({
      showShop: !this.data.showShop,
      chooseTime: '',
      coach_id: '',
    });

    // var type = 'top';
    // this.setData({
    //   [`show.${type}`]: !this.data.show[type],
    //   [`show.date`]: false
    // });
  },

  toggleDatePopup() {
    if (this.showShop) {
      this.toggleTopPopup();
    }
    var type = 'date';
    this.setData({
      [`show.${type}`]: !this.data.show[type],
      [`show.top`]: false,
      chooseTime: '',
      // coach_id: '',
      // times:[],
    });
  },

  selectCity: function (e) {
    var that = this;
    let name = e.currentTarget.dataset.name
    var activeDistrictName = that.data.districts[name][0]
    that.setData({
      activeCityName: name,
      //activeDistrictName: that.data.site.district,
      sites: that.getCitySite(name)
    })
  },

  getCitySite: function (city) {
    var that = this;
    var citySites = that.data.availableSites[city];
    var result = [];
    for (var key in citySites) {
      for (var j in citySites[key]) {
        result.push(citySites[key][j]);
      }

    }
    return result;
  },

  selectDistrict: function (e) {
    var that = this;
    let name = e.currentTarget.dataset.name
    that.setData({
      activeDistrictName: name,
      sites: that.data.availableSites[that.data.activeCityName][name]
    })
  },

  selectSite: function (e) {

    var that = this;
    let id = e.currentTarget.dataset.id
    let district = e.currentTarget.dataset.district
    let siteName = e.currentTarget.dataset.name
    that.setData({
      activeSiteId: id,
      activeDistrictName: district,
      siteId: id,
      siteName: siteName
    })
    //    let that = this;
    // this.toggle('top');
    this.setData({
      times: [],
      activeSiteName: this.data.siteName,
      showShop: false
    })
    if (!that.data.showCoach)
      that.toggleCoach();
    that.listAvailableTime();
    // that.listAvailableCoach();
  },

  generateData: function (res) {
    var that = this;
    let citys = [],
      district = [],
      sites = {};

    let json = res.data

    var originSite = json.data.site;
    var originAvailableSites = json.data.availableSites;
    that.setData({
      site: originSite,
      availableSites: originAvailableSites
    })

    that._getSelectData();

  },

  _getSelectData() {
    var that = this;
    var site = that.data.site;
    var availableSites = that.data.availableSites;

    var citys = [];
    var districts = {};
    var sites = {};
    var all_sites = [];
    for (var i in availableSites) {
      var siteCount = 0;
      var siteName = i;
      var districtSites = availableSites[i];
      var districtNames = [];
      for (var j in districtSites) {
        districtNames.push(j);
        siteCount = siteCount + districtSites[j].length;
      }
      citys.push({
        name: siteName,
        count: siteCount
      })
      districts[i] = districtNames;

      //  new loop
      var all_sites_hash = {};
      all_sites_hash['city'] = {
        name: siteName,
        count: siteCount
      }
      var tmp_arry = []
      for (var j in districtSites) {
        for (var k in districtSites[j]) {

          tmp_arry.push(districtSites[j][k]);
        }
      }
      all_sites_hash['sites'] = tmp_arry;
      all_sites.push(all_sites_hash);
    }
    console.log('all_sites')
    console.log(all_sites)

    that.setData({
      citys: citys,
      districts: districts,
      activeCityName: site.city,
      activeDistrictName: site.district,
      activeSiteId: site.id,
      sites: availableSites[site.city][site.district],
      activeSiteName: site.alias,
      all_sites: all_sites,
      // availableSites: availableSites,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */

  // this.setData({
  //   host: constant.api(app.globalData.pord).url,
  //   unionid: wx.getStorageSync(storage.keys.unionid),
  //   FU_XING: constant.resource.FU_XING,
  //   courseRoundId: options.courseRoundId,
  //   siteId: options.siteId,
  //   occurDate: options.occurDate,
  //   occurHour: options.occurHour
  // });
  onLoad: function (options) {
    var that = this;
    that.setData({
      host: constant.api(app.globalData.pord).url,
      unionid: wx.getStorageSync(storage.keys.unionid),
      FU_XING: constant.resource.FU_XING,
      courseRoundId: options.courseRoundId,
      qiniu: constant.resource.qiniu,
    })
    if (options.scheduleId) {
      that.setData({
        scheduleId: options.scheduleId
      });
    }

    wx.request({
      url: that.data.host + '/profile/courses/' + that.data.courseRoundId + '/available-sites?unionid=' + that.data.unionid,
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function (res) {
        var data = res.data.data
        if (res.data.code == "0") {
          if (data.availableSites && Object.keys(data.availableSites).length > 0) {
            that.generateData(res);
          }
        } else {}
      },
      fail: function (res) {}
    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.showLoading({
      title: "正在加载中..."
    });

    var that = this;

    wx.request({
      url: that.data.host + '/profile/courses/' + that.data.courseRoundId + '/available-days?unionid=' + that.data.unionid + '&scheduleId=' + (that.data.scheduleId ? that.data.scheduleId : ''),
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function (res) {
        var data = res.data.data
        if (res.data.code == "0") {
          that.setData({
            days: res.data.data.availableDays
          });

          wx.hideLoading();
        } else {
          wx.hideLoading();

          wx.showToast({
            title: res.data.message ? res.data.message : '请求失败',
            icon: 'none',
            duration: 1000
          })
        }
      },
      fail: function (res) {
        wx.hideLoading();

        wx.showToast({
          title: '请求数据失败',
          icon: 'none',
          duration: 1000
        });
      }
    });


    that.listAvailableTime();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  gotoDetails: function (e) {
    var that = this;
    // this.setData({
    //   chooseDay: e.currentTarget.dataset.date
    // })
    if (e.currentTarget.dataset.time)
      console.log(e.currentTarget.dataset.time)
    wx.navigateTo({
      url: "/pages/user-course/user-course-detail/course-schedule/course-schedule-detail/course-schedule-detail?scheduleId=" + e.currentTarget.dataset.time

    })

  },

  submitOrder: function () {
    var that = this;
    if (!that.data.chooseDay) {
      return 0;
    }
    if (!that.data.chooseTime) {
      return 0;
    }
    if (!that.data.siteId) {
      return 0;
    }
    if (!that.data.coach_id) {
      return 0;
    }
    var content = that.data.chooseDay + ' ' + that.data.chooseTime + '\r\n  ' + that.data.activeSiteName + ' ' + that.data.selectedCoach;
    wx.requestSubscribeMessage({
      tmplIds: ['qHMvm62m-7mWwIUTeip6r2dcUiPgV4D1lutXaAdhij8'],
      success (res) {
        wx.showModal({
          title: '确认预约',
          content: content,
          showCancel: true, //是否显示取消按钮
          cancelText: "否", //默认是“取消”
          // cancelColor:'skyblue',//取消文字的颜色
          confirmText: "是", //默认是“确定”
          // confirmColor: 'skyblue',//确定文字的颜色
          success: function (res) {
            if (res.cancel) {
              //点击取消,默认隐藏弹框
            } else {
              wx.request({
                url: that.data.host + '/profile/courses/' + that.data.courseRoundId + '/appoint?unionid=' + that.data.unionid + '&scheduleId=' + (that.data.scheduleId ? that.data.scheduleId : ''),
                method: 'POST',
                data: {
                  site_id: that.data.siteId,
                  coach_id: that.data.coach_id,
                  occur_date: that.data.chooseDay,
                  occur_hour: that.data.chooseTime
                },
                header: {
                  'content-type': 'application/json'
                },
                success: function (res) {
                  if (res.data.code == "0") {
                    wx.showToast({
                      title: res.data.message,
                      icon: 'success',
                      duration: 1000,
                      mask: true,
                      success: function () {
                        setTimeout(function () {
                          // wx.navigateBack({
                          //   delta: 1
                          // });
                          that.setData({
                            isNeedSurvey: res.data.data.isNeedSurvey
                          })
                          if(!that.data.isNeedSurvey) {
                            wx.navigateBack({
                              delta: 1
                            });
                          }
                        }, 1000)
                      }
                    });
    
                  } else {
                    that.setData({
                      disabled: false
                    })
                    wx.showToast({
                      title: res.data.message ? res.data.message : '请求失败',
                      icon: 'none',
                      duration: 3000,
                      mask: true
                    })
                  }
                },
                fail: function (res) {
                  that.setData({
                    disabled: false
                  })
                  wx.showToast({
                    title: '预约失败',
                    icon: 'none',
                    duration: 3000,
                    mask: true
                  })
                }
              });
    
            }
          },
          fail: function (res) {}, //接口调用失败的回调函数
          complete: function (res) {}, //接口调用结束的回调函数（调用成功、失败都会执行）
        })
      }
    })
    

    // var that = this;
    // console.log(this.data.chooseTime)




  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  listAvailableTime: function () {
    var that = this;

    wx.request({
      url: that.data.host + '/profile/courses/' + that.data.courseRoundId + '/available-times?unionid=' + that.data.unionid + '&day=' + (that.data.day ? that.data.day : '') + '&siteId=' + (that.data.siteId ? that.data.siteId : '') + '&scheduleId=' + (that.data.scheduleId ? that.data.scheduleId : ''),
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function (res) {
        if (res.data.code == "0") {
          that.setData({
            day: res.data.data.day,
            chooseDay: res.data.data.day,
            siteId: res.data.data.site.id,
            roomLimit: res.data.data.site.room_limit.room_limit,
            commonLimit: res.data.data.site.room_limit.common_limit,
            remains: res.data.data.remainList
          });
          wx.request({
            url: constant.api(app.globalData.pord).url+'/xh/api/principle/get/',
            method: 'POST',
            data: {
              site: that.data.siteId,
              courseRoundId: that.data.courseRoundId,
              date: that.data.chooseDay,
            },
            dataType: 'json',
            responseType: 'text',
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            success: function (res) {
              that.setData({
                coaches: res.data,
              });
              wx.request({
                url: that.data.host + '/profile/courses/' + that.data.courseRoundId + '/specialTags?unionid=' + that.data.unionid + '&siteId=' + (that.data.siteId ? that.data.siteId : ''),
                method: 'GET',
                dataType: 'json',
                responseType: 'text',
                success: function (res) {
                  if (res.data.data.roundSpecial) {
                    debugger
                    that.setData({
                      roundSpecial: res.data.data.roundSpecial,
                      specialTags: res.data.data.specialTags
                    })

                    if (res.data.data.specialType && res.data.data.specialType == 'special') {
                      var coaches = that.data.coaches;
                      var results = [];
                      for (var i in coaches) {
                        //console.log(res.data.data.specialTags[coaches[i].id])
                        if (res.data.data.specialTags[coaches[i].id]) {
                          //console.log(res.data.data.specialTags[coaches[i].id].indexOf(that.data.roundSpecial))
                          //console.log(that.data.roundSpecial)
                          if (res.data.data.specialTags[coaches[i].id].indexOf(that.data.roundSpecial) != -1) {
                            coaches[i].specialTags = res.data.data.specialTags[coaches[i].id];
                            results.push(coaches[i]);
                          }
                        }
                      }
                      console.log(results)
                      that.setData({
                        coaches: results,
                        showTags: true
                      })
                    } else if (res.data.data.specialType && res.data.data.specialType == 'posture') {
                      debugger
                      var coaches = that.data.coaches;
                      var results = [];
                      for (var i in coaches) {
                        if (res.data.data.specialTags[coaches[i].id]) {
                          if (res.data.data.specialTags[coaches[i].id].indexOf(that.data.roundSpecial) != -1) {
                            results.push(coaches[i]);
                          }
                        }
                      }
                      that.setData({
                        coaches: results
                      })
                    } else if (res.data.data.specialType && res.data.data.specialType == 'year') {
                      var coaches = that.data.coaches;
                      var results = [];
                      for (var i in coaches) {
                        if (res.data.data.specialTags[coaches[i].id]) {
                          if (res.data.data.specialTags[coaches[i].id] != "8") {
                            coaches[i].specialTags = res.data.data.specialTags[coaches[i].id];
                          }
                        }
                        results.push(coaches[i]);
                      }
                      that.setData({
                        coaches: results,
                        showTags: true
                      })
                    }
                  } else {
                    debugger
                    if (res.data.data.roundUnit) {
                      if(res.data.data.roundUnit == 'special_week_experience') {
                        var coaches = that.data.coaches;
                        for (var i in coaches) {
                          if (res.data.data.specialTags[coaches[i].id]) {
                            coaches[i].specialTags = res.data.data.specialTags[coaches[i].id];
                          }
                        }
                        console.log(coaches)
                        that.setData({
                          coaches: coaches,
                          showTags: true
                        })
                      } else if (res.data.data.roundUnit.indexOf("special") < 0) {
                        var coaches = that.data.coaches;
                        for (var i in coaches) {
                          if (res.data.data.specialTags[coaches[i].id]) {
                            coaches[i].specialTags = res.data.data.specialTags[coaches[i].id];
                          }
                        }
                        console.log(coaches)
                        that.setData({
                          coaches: coaches,
                          showTags: true
                        })
                      }

                    } 
                    
                    // else {
                    //   var coaches = that.data.coaches;
                    //   for (var i in coaches) {
                    //     if (res.data.data.specialTags[coaches[i].id]) {
                    //       coaches[i].specialTags = res.data.data.specialTags[coaches[i].id];
                    //     }
                    //   }
                    //   console.log(coaches)
                    //   that.setData({
                    //     coaches: coaches
                    //   })
                    // }
                  }
                },
                fail: function (res) {
                  if (res.data.code != '404') {
                    wx.showToast({
                      title: '请求数据失败',
                      icon: 'none',
                      duration: 1000
                    });
                  }
                }
              })
            },
            fail: function (res) {
              wx.showToast({
                title: '请求数据失败',
                icon: 'none',
                duration: 1000
              });
            }
          })
        } else {
          wx.showToast({
            title: res.data.message ? res.data.message : '请求失败',
            icon: 'none',
            duration: 1000
          })
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '请求数据失败',
          icon: 'none',
          duration: 1000
        });
      }
    })


  },

  listAvailableCoach: function () {
    var that = this;

    wx.request({
      url: constant.api(app.globalData.pord).url+'/xh/api/principle/get/',
      method: 'POST',
      data: {
        site: that.data.siteId,
        courseRoundId: that.data.courseRoundId,
        date: that.data.chooseDay,
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      dataType: 'json',
      responseType: 'text',
      success: function (res) {
        //  success
      },
      fail: function (res) {
        wx.showToast({
          title: '请求数据失败',
          icon: 'none',
          duration: 1000
        });
      }
    })
  },

  chooseDate: function (e) {
    var that = this;
    this.setData({
      chooseDay: e.currentTarget.dataset.date
    })
    this.setData({
      day: that.data.chooseDay
    })
    that.listAvailableTime();
    var type = 'date'
    this.setData({
      [`show.${type}`]: !this.data.show[type],
      [`show.top`]: false
    });
    if (that.data.coach_id) {
      wx.request({
        url: constant.api(app.globalData.pord).url+'/xh/api/principle/get_date/',
        method: 'POST',
        data: {
          coach_id: that.data.coach_id,
          date: that.data.chooseDay,
          union_id: that.data.unionid,
          scheduleId: that.data.scheduleId,
          siteId: that.data.siteId,

        },
        dataType: 'json',
        responseType: 'text',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function (res) {
          //  success
          that.setData({
            times: res.data,
          });
          console.log(res.data)
          if (that.data.showCoach)
            that.toggleCoach();
        },
        fail: function (res) {
          wx.showToast({
            title: '请求数据失败',
            icon: 'none',
            duration: 1000
          });
        }
      })
    } else {
      this.setData({
        times: []
      })
    }
  },


  chooseTime: function (e) {
    console.log('chooseTime')
    var that = this;
    if (e.currentTarget.dataset.a == 1) {
      this.setData({
        chooseTime: e.currentTarget.dataset.time.time
      })
    }
    console.log(that.data.chooseTime)

  },

  selectDate: function (e) {
    var that = this;
    this.setData({
      day: that.data.chooseDay
    })
    that.listAvailableTime();
    var type = 'date'
    this.setData({
      [`show.${type}`]: !this.data.show[type],
      [`show.top`]: false
    });



  },

  submitSitesData: function (e) {
    let that = this;
    this.toggle('top');
    this.setData({
      activeSiteName: this.data.siteName
    })

    that.listAvailableTime();

  },

})